<template>
  <div class="emp-table-page">
    <el-card>
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center">
          <span>职位管理</span>
          <div style="display: flex; align-items: center; gap: 8px">
            <el-button @click="refreshCurrentMode" :loading="loading">刷新</el-button>
            <el-button v-if="!postMode" @click="openConditionDialog">条件查询</el-button>
            <el-button v-if="postMode" @click="switchToGet">重置为全部</el-button>
          </div>
        </div>
      </template>
      <el-table :data="userList" v-loading="loading" style="width: 100%; margin-bottom: 16px">
        <el-table-column prop="id" label="职位id" width="60" />
        <el-table-column prop="title" label="职位名称" width="120" />
        <el-table-column prop="salary" label="薪水" width="100" />
        <el-table-column prop="companyName" label="公司名称" width="140" />
        <el-table-column prop="companySize" label="公司规模" width="70" />
        <el-table-column prop="location" label="公司所在地" width="80" />

        <el-table-column prop="experience" label="经验要求" width="80" />
        <el-table-column prop="education" label="学历要求" width="100" />
        <el-table-column prop="type" label="职位类型" width="60" />
        <el-table-column prop="benefits" label="职位待遇福利" width="180" />
        <el-table-column fixed="right" label="操作" width="240">
          <template #default="scope">
            <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              :loading="deleteLoadingId === scope.row.id"
            >
              删除
            </el-button>
            <el-button
              size="small"
              type="warning"
              @click="handleDeleteC(scope.row)"
              :loading="deleteLoadingC === scope.row.companyName"
            >
              删除公司
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div
      style="display: flex; justify-content: space-between; align-items: center; margin-top: 8px"
    >
      <!-- 左侧分页控件 -->
      <el-pagination
        background
        layout="prev, pager, next, jumper, ->, total"
        :total="total"
        :page-size="pageSize"
        :current-page="pageNum"
        @current-change="handlePageChange"
      />

      <!-- 右侧跳转功能 -->
      <div style="display: flex; align-items: center; gap: 8px">
        <div style="display: flex; align-items: center; gap: 4px">
          <!-- <span style="font-size: 12px">每页条数：</span> -->
          <span style="display: flex; align-items: center; gap: 4px">每页条数：</span>
          <el-input-number
            v-model="inputPageSize"
            :min="1"
            :max="100"
            size="small"
            style="width: 100px"
            :step="1"
            placeholder="每页条数"
          />
        </div>
        <!-- <el-button size="small" @click="applyPageInput">跳转分页</el-button> -->
        <el-button @click="applyPageInput">跳转分页</el-button>
      </div>
    </div>

    <!-- 条件查询弹窗 -->
    <el-dialog title="条件查询" v-model="conditionDialogVisible" width="500px">
      <el-form :model="conditionForm" label-width="90px">
        <el-form-item label="职位名称">
          <el-input v-model="conditionForm.title" clearable />
        </el-form-item>

        <el-form-item label="薪水">
          <!-- 只允许输入数字可改 el-input-number -->
          <el-input v-model="conditionForm.salary" clearable />
        </el-form-item>

        <el-form-item label="公司名称">
          <el-input v-model="conditionForm.companyName" clearable />
        </el-form-item>

        <el-form-item label="公司规模">
          <el-select v-model="conditionForm.companySize" clearable placeholder="请选择">
            <el-option label="大型" value="大型" />
            <el-option label="中型" value="中型" />
            <el-option label="小型" value="小型" />
          </el-select>
        </el-form-item>

        <el-form-item label="公司所在地">
          <el-input v-model="conditionForm.location" clearable />
        </el-form-item>

        <el-form-item label="经验要求">
          <el-select v-model="conditionForm.experience" clearable placeholder="请选择">
            <el-option label="1年以上" value="1年以上" />
            <el-option label="2年以上" value="2年以上" />
            <el-option label="3年以上" value="3年以上" />
            <el-option label="4年以上" value="4年以上" />
            <el-option label="5年以上" value="5年以上" />
          </el-select>
        </el-form-item>

        <el-form-item label="学历要求">
          <el-select v-model="conditionForm.education" clearable placeholder="请选择">
            <el-option label="大专及以上" value="大专及以上" />
            <el-option label="本科及以上" value="本科及以上" />
            <el-option label="硕士及以上" value="硕士及以上" />
          </el-select>
        </el-form-item>

        <el-form-item label="职位类型">
          <el-select v-model="conditionForm.type" clearable placeholder="请选择">
            <el-option label="兼职" value="兼职" />
            <el-option label="全职" value="全职" />
          </el-select>
        </el-form-item>

        <el-form-item label="职位待遇福利">
          <el-input v-model="conditionForm.benefits" clearable />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="conditionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="applyCondition">查询</el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑用户弹窗 -->
    <el-dialog
      :title="dialogMode === 'add' ? '添加用户' : '编辑用户'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
        <!-- <el-form :model="form" label-width="90px"> -->
        <el-form-item label="职位名称">
          <el-input v-model="form.title" clearable />
        </el-form-item>

        <el-form-item label="薪水">
          <el-input v-model="form.salary" clearable />
        </el-form-item>

        <el-form-item label="公司名称">
          <el-input v-model="form.companyName" clearable />
        </el-form-item>

        <el-form-item label="公司规模">
          <el-select v-model="form.companySize" clearable placeholder="请选择">
            <el-option label="大型" value="大型" />
            <el-option label="中型" value="中型" />
            <el-option label="小型" value="小型" />
          </el-select>
        </el-form-item>

        <el-form-item label="公司所在地">
          <el-input v-model="form.location" clearable />
        </el-form-item>

        <el-form-item label="经验要求">
          <el-select v-model="form.experience" clearable placeholder="请选择">
            <el-option label="1年以上" value="1年以上" />
            <el-option label="2年以上" value="2年以上" />
            <el-option label="3年以上" value="3年以上" />
            <el-option label="4年以上" value="4年以上" />
            <el-option label="5年以上" value="5年以上" />
          </el-select>
        </el-form-item>

        <el-form-item label="学历要求">
          <el-select v-model="form.education" clearable placeholder="请选择">
            <el-option label="大专及以上" value="大专及以上" />
            <el-option label="本科及以上" value="本科及以上" />
            <el-option label="硕士及以上" value="硕士及以上" />
          </el-select>
        </el-form-item>

        <el-form-item label="职位类型">
          <el-select v-model="form.type" clearable placeholder="请选择">
            <el-option label="兼职" value="兼职" />
            <el-option label="全职" value="全职" />
          </el-select>
        </el-form-item>

        <el-form-item label="职位待遇福利">
          <el-input v-model="form.benefits" clearable />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="dialogLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
//import { getUserList, addUser, updateUser, deleteUser, getAllUsers } from '@/api/user'
import { getEmpList, addEmp, updateEmp, deleteEmp, getAllEmps, deleteEmpByName } from '@/api/emp'
import { showCustomMessage } from '@/utils/message'
import type { FormInstance, FormRules } from 'element-plus'

const userList = ref<any[]>([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const inputPageNum = ref(1)
const inputPageSize = ref(10)
const loading = ref(false)
const dialogVisible = ref(false)
const dialogMode = ref<'add' | 'edit'>('add')
const dialogLoading = ref(false)
const deleteLoadingId = ref<string | null>(null)
const deleteLoadingC = ref<string | null>(null)
const formRef = ref<FormInstance>()
const postMode = ref(false) // false: GET分页所有，true: GET分页条件
const conditionDialogVisible = ref(false)
const conditionForm: Record<string, any> = reactive({
  id: undefined,
  type: '',
  benefits: '',
  title: '',
  salary: '',
  companyName: '',
  companySize: '',
  location: '',
  experience: '',
  education: '',
})
let lastCondition: Record<string, any> = {} // 记录上次查询条件

const form = reactive({
  id: undefined,
  type: '',
  benefits: '',
  title: '',
  salary: '',
  companyName: '',
  companySize: '',
  location: '',
  experience: '',
  education: '',
})

const rules: FormRules = {
  type: [{ required: true, message: '请选择职位类型', trigger: 'blur' }],
  title: [{ required: true, message: '请输入职位名称', trigger: 'blur' }],
  salary: [{ required: true, message: '请输入预计薪资', trigger: 'blur' }],
  companyName: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
  companySize: [{ required: true, message: '请选择公司规模', trigger: 'blur' }],
  location: [{ required: true, message: '请输入公司所在地', trigger: 'blur' }],
  experience: [{ required: true, message: '请选择至少几年经验', trigger: 'blur' }],
  education: [{ required: true, message: '请选择期望的学历', trigger: 'change' }],
}

// GET分页获取所有用户
const fetchEmpsGet = async () => {
  loading.value = true
  try {
    const response = await getAllEmps({ pageNum: pageNum.value, pageSize: pageSize.value })
    userList.value = response.data.list || []
    total.value = response.data.total || response.data.length || 0
    postMode.value = false
    showCustomMessage('GET分页获取所有用户成功', 'success')
  } catch (error: any) {
    showCustomMessage('GET分页获取所有用户失败: ' + error.message, 'error')
  } finally {
    loading.value = false
  }
}

// GET分页条件查询用户
const fetchEmpsPost = async (condition: Record<string, any> = {}) => {
  loading.value = true
  try {
    // 只传递有值的条件
    const params: Record<string, any> = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      ...condition,
    }
    Object.keys(params).forEach((key) => {
      if (params[key] === '' || params[key] === undefined || params[key] === null) {
        delete params[key]
      }
    })
    const response = await getEmpList(params)
    userList.value = response.data.list || []
    total.value = response.data.total || response.data.length || 0
    postMode.value = true
    showCustomMessage('GET分页条件查询成功', 'success')
  } catch (error: any) {
    showCustomMessage('GET分页条件查询失败: ' + error.message, 'error')
  } finally {
    loading.value = false
  }
}

const openConditionDialog = () => {
  conditionDialogVisible.value = true
}

const applyCondition = () => {
  pageNum.value = 1
  inputPageNum.value = 1
  // 记录本次条件
  lastCondition = { ...conditionForm }
  conditionDialogVisible.value = false
  fetchEmpsPost(lastCondition)
}

const switchToPost = () => {
  pageNum.value = 1
  inputPageNum.value = 1
  openConditionDialog()
}

const switchToGet = () => {
  pageNum.value = 1
  inputPageNum.value = 1
  // 清空条件
  Object.keys(conditionForm).forEach((key) => (conditionForm[key] = undefined))
  lastCondition = {}
  fetchEmpsGet()
}

const refreshCurrentMode = () => {
  if (postMode.value) {
    fetchEmpsPost(lastCondition)
  } else {
    fetchEmpsGet()
  }
}

const handlePageChange = (val: number) => {
  pageNum.value = val
  inputPageNum.value = val
  refreshCurrentMode()
}

const applyPageInput = () => {
  if (inputPageNum.value < 1) inputPageNum.value = 1
  if (inputPageSize.value < 1) inputPageSize.value = 1
  pageNum.value = inputPageNum.value
  pageSize.value = inputPageSize.value
  refreshCurrentMode()
}

const openAddDialog = () => {
  dialogMode.value = 'add'
  Object.assign(form, {
    username: '',
    nickname: '',
    password: '',
    name: '',
    phone: '',
    email: '',
    age: 18,
    sex: 1,
    eduBack: '',
    salaryWishK: 0,
    address: '',
    introduction: '',
    hasExperience: 0,
  })
  dialogVisible.value = true
}

const openEditDialog = (row: any) => {
  dialogMode.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    dialogLoading.value = true
    try {
      if (dialogMode.value === 'add') {
        await addEmp(form)
        showCustomMessage('添加用户成功', 'success')
      } else {
        await updateEmp(form)
        showCustomMessage('编辑用户成功', 'success')
      }
      dialogVisible.value = false
      refreshCurrentMode()
    } catch (error: any) {
      showCustomMessage(
        (dialogMode.value === 'add' ? '添加' : '编辑') + '用户失败: ' + error.message,
        'error',
      )
    } finally {
      dialogLoading.value = false
    }
  })
}

const handleDelete = async (row: any) => {
  if (!row.id) return
  if (!confirm(`确定要删除职位 ${row.id} 吗？`)) return
  deleteLoadingId.value = row.id
  try {
    await deleteEmp(row.id)
    showCustomMessage('删除职位成功', 'success')
    refreshCurrentMode()
  } catch (error: any) {
    showCustomMessage('删除职位失败: ' + error.message, 'error')
  } finally {
    deleteLoadingId.value = null
  }
}

const handleDeleteC = async (row: any) => {
  if (!row.companyName) return
  if (!confirm(`确定要删除公司 ${row.companyName} 吗？`)) return
  deleteLoadingC.value = row.companyName
  try {
    await deleteEmpByName(row.companyName)
    showCustomMessage('删除公司成功', 'success')
    refreshCurrentMode()
  } catch (error: any) {
    showCustomMessage('删除公司失败: ' + error.message, 'error')
  } finally {
    deleteLoadingC.value = null
  }
}

onMounted(() => {
  fetchEmpsGet()
})
</script>

<style scoped>
.user-table-page {
  padding: 20px;
}
</style>
